package com.haiertvbic.tvwa;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.haiertvbic.tvwa.model.FavChannelBean;
import com.haiertvbic.tvwa.model.FavChannelPagekage;
import com.haiertvbic.tvwa.model.SingleHandler;
import com.haiertvbic.tvwa.protocol.CAEProtocol;
import com.haiertvbic.tvwa.util.AppManager;
import com.haiertvbic.tvwa.util.Constant;
import com.haiertvbic.tvwa.util.LocateToast;
import com.haiertvbic.tvwa.util.ProduceThread;
import com.haiertvbic.tvwa.util.SLog;
import com.haiertvbic.tvwa.util.SetActivityView;
import com.haiertvbic.tvwa.util.SwitchChannel;

/*
 * 修改后第一屏没问题，第二屏获取不到数据
 */
public class FavoriteChannelActivity extends Activity {
	// 显示加载进度
	private ProgressBar cha_bar;
	// 显示排名的频道
	private ListView chaListView;
	// 显示操作时间提示
	public static TextView showTime_1;
	// 从CAE获取的返回的数据包
	private FavChannelPagekage favChaPkg;
	private Void channelList;
	private int return_code;// 从CAE获取频道列表数据的返回码
	private int cha_count;// 喜爱频道的个数
	private int which;
	private int[] cha_id;
	private String[] cha_names;
	public static View fView;
	private boolean canToNext;
	private boolean canSwitch;
	private final int INSTANCE_NULL = 3;
	private final int DB_ERRO = 1;
	private final int UNKNOW_ERRO = 2;
	private Handler handleCAE;
	private String action = "com.haiertvbic.tvwa.TVWA_LAUNCH";// 窗口被按键调出后给VD发广播，开机三分钟后不要再调出窗口
	private int currentCha = -200;
	private int switchCha = -200;
	private MyFavChasAdapter adapter;
	// 从CAE获取我喜爱的频道
	private ArrayList<FavChannelBean> myFavoriteChannels;
	private Handler myHandler;
	// 显示加载进度对话框
	// private ProgressDialog progressDialog;
	// 没有获取频道数据
	private static final int GET_FAVCHAS_FAIL = 100000;
	// 获取频道数据成功
	private static final int GET_FAVCHAS_SUC = 100002;
	// 数据库错误
	private static final int DB_ERROR = 100003;
	// 未知错误
	private static final int NOT_SURE_ERROR = 100004;

	/**
	 * 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		initView();
		// 设置窗体的样式
		fView = SetActivityView
				.setActivityView(getWindow(), getWindowManager());
		SLog.d("lfav", "zhixing dao 1");
		Intent brodcastIntent = new Intent();
		brodcastIntent.setAction(action);
		// 发送窗口启动的广播，开机三分钟后不再调出
		sendBroadcast(brodcastIntent);
		
		SLog.d("lfav", "zhixing dao2 !!");
		SingleHandler sHandler = SingleHandler.returnHandler();
		sHandler.setTextView(showTime_1);
		SLog.d("lfav", "zhixing dao 3!!");
		ProduceThread.produceThread(sHandler);
		SLog.d("lfav", "zhixing dao 4!!");
		AppManager.activityList.add(this);

		myHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case GET_FAVCHAS_FAIL:
					// 获取频道数据失败，消失加载数据进度条
					// progressDialog.dismiss();
					cha_bar.setVisibility(View.GONE);
					Toast.makeText(FavoriteChannelActivity.this, "获取频道数据失败",
							Toast.LENGTH_SHORT).show();
					break;
				case GET_FAVCHAS_SUC:
					// 获取数据成功，适配显示数据，消失加载数据的进度条
					// progressDialog.dismiss();
					cha_bar.setVisibility(View.GONE);
					showChannels(myFavoriteChannels);
					canToNext = true;
					canSwitch = true;
					break;
				case DB_ERROR:
					// 数据库错误
					// progressDialog.dismiss();
					cha_bar.setVisibility(View.GONE);
					Toast.makeText(FavoriteChannelActivity.this, "操作数据库出错",
							Toast.LENGTH_SHORT).show();
					break;
				case NOT_SURE_ERROR:
					// 不确定的错误
					// progressDialog.dismiss();
					cha_bar.setVisibility(View.GONE);
					Toast.makeText(FavoriteChannelActivity.this, "不确定的错误",
							Toast.LENGTH_SHORT).show();
					break;

				case 0:
					LocateToast.locateToast(FavoriteChannelActivity.this, 200,
							"读取换台信息失败");
					break;

				case 4004500:
					LocateToast.locateToast(FavoriteChannelActivity.this, 200,
							"换台成功 ");
					currentCha = switchCha;
					break;

				case 4004501:
					LocateToast.locateToast(FavoriteChannelActivity.this, 200,
							"此频道不存在");
					break;

				case 4004502:
					LocateToast.locateToast(FavoriteChannelActivity.this, 200,
							"请插入或重新插拔CRB");
					break;

				case 4004503:
					LocateToast.locateToast(FavoriteChannelActivity.this, 200,
							"您未设置 CRB");
					break;

				case -2002:
					LocateToast.locateToast(FavoriteChannelActivity.this, 200,
							"连接断开");
					break;

				default:
					break;
				}
			}
		};

		// 从CAE获取喜爱的频道数据
		getFavChaFromCae();
	}

	private void showChannels(ArrayList<FavChannelBean> favChannels) {
		adapter = new MyFavChasAdapter(FavoriteChannelActivity.this,
				favChannels);
		chaListView.setAdapter(adapter);
	}

	private void getFavChaFromCae() {
		cha_bar.setVisibility(View.VISIBLE);
		// progressDialog.show();
		Thread getFavChasThread = new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();

				favChaPkg = CAEProtocol.getFavChannel(1, 5);

				if (favChaPkg == null) {
					// 获取数据失败
					myHandler.sendEmptyMessage(GET_FAVCHAS_FAIL);
				} else if (favChaPkg.getReturn_code() == 4006002
						|| favChaPkg.getReturn_code() == 4006003) {
					// 操作数据库失败
					myHandler.sendEmptyMessage(DB_ERROR);
				} else if (favChaPkg.getReturn_code() == 4006000
						|| favChaPkg.getReturn_code() == 4006001) {
					// 获取数据成功
					myFavoriteChannels = favChaPkg.getChannels();
					if (myFavoriteChannels != null) {
						cha_count = myFavoriteChannels.size();
						SLog.d("lfav", "myFavoriteChannels de changdu ====="
								+ myFavoriteChannels.size());
						cha_names = new String[cha_count];
						cha_id = new int[cha_count];
						for (int i = 0; i < cha_count; i++) {
							FavChannelBean channelBean = myFavoriteChannels
									.get(i);

							SLog.d("lfav", "channelBean de jiemu id ===="
									+ channelBean.getChannel_id());

							SLog.d("lfav", "channelBean de jiemu ming zi  ===="
									+ channelBean.getChannel_name());
							cha_names[i] = channelBean.getChannel_name();
							cha_id[i] = channelBean.getChannel_id();
						}
//						SLog.d("lfav", "cha_names  ===" + cha_names);
//						SLog.d("lfav", "cha_id  ===" + cha_id);

//						if (cha_names != null) {
//							SLog.d("lfav", "cha_names.legth  ==="
//									+ cha_names.length);
//
//							for (int i = 0; i < cha_names.length; i++) {
//								SLog.d("lfav", "cha_names " + i + "  == "
//										+ cha_names[i]);
//							}
//						}
//
//						if (cha_id != null) {
//							SLog.d("lfav", "cha_id.legth  ===" + cha_id.length);
//							for (int i = 0; i < cha_id.length; i++) {
//								SLog.d("lfav", "cha_id " + i + "  == " + cha_id[i]);
//							}
//						}
					}

					myHandler.sendEmptyMessage(GET_FAVCHAS_SUC);
				} else if (favChaPkg.getReturn_code() == 4006004) {
					// 发生未知错误
					myHandler.sendEmptyMessage(NOT_SURE_ERROR);
				}

			}

		};
		getFavChasThread.start();
	}

	@Override
	protected void onStart() {
		super.onStart();
		// new ChannelAsyncTask().execute(channelList);
	}


	/**
	 * 初始化控件
	 */
	private void initView() {
		chaListView = (ListView) findViewById(R.id.cha_list);
		showTime_1 = (TextView) findViewById(R.id.show_time_1);
		cha_bar = (ProgressBar) findViewById(R.id.cha_bar);
		// progressDialog = new ProgressDialog(FavoriteChannelActivity.this);
		chaListView.setOnItemSelectedListener(new OnItemSelectedListener() {
			boolean first = false;

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				which = arg2;
				if (first) {
					ProduceThread.seconds = Constant.SECOND_TIME;
				}
				first = true;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		chaListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {// TODO Auto-generated method stub
				SLog.d("zlm", "cha_id == " + cha_id);
				SLog.d("zlm", "canSwitch == " + canSwitch);
				if (cha_id != null) {
					for (int i = 0; i < cha_id.length; i++) {
						SLog.d("zlm", "cha_id " + i + " == " + cha_id[i]);
					}

				}
				if (canSwitch && cha_id != null && currentCha != cha_id[arg2]) {
					SwitchChannel.switchChannel(FavoriteChannelActivity.this,
							cha_id[arg2], myHandler);
					switchCha = cha_id[arg2];
				}
				ProduceThread.seconds = Constant.SECOND_TIME;
			}
		});
	}

	/**
	 * 处理右按键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		ProduceThread.seconds = Constant.SECOND_TIME;
		if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			if (canToNext) {
				Intent intent = new Intent();
				intent.putExtra("CHA_NAME", myFavoriteChannels.get(which)
						.getChannel_name());
				intent.putExtra("CHA_ID", myFavoriteChannels.get(which)
						.getChannel_id());
				SLog.v("lfav", "na ge pin dao de jiemu ===="
						+ myFavoriteChannels.get(which).getChannel_name()+"+"+myFavoriteChannels.get(which)
						.getChannel_id());
				intent.setClass(this, ChannelProActivity.class);
				startActivity(intent);
				SLog.v("lfav", "跳转第二个界面");
				fView.setVisibility(View.INVISIBLE);
				/*
				 * Intent intent = new Intent(); intent.putExtra("CHA_NAME",
				 * cha_names[which]); intent.putExtra("CHA_ID", cha_id[which]);
				 * SLog.v("lfav", cha_names[which]); // Toast.makeText(this, ""
				 * + cha_type_id[which], 1000).show(); intent.setClass(this,
				 * ChannelProActivity.class); startActivity(intent);
				 * fView.setVisibility(View.INVISIBLE);
				 */
			}
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			ProduceThread.canRun = false;
			// progressDialog = null;
		} else if (keyCode == KeyEvent.KEYCODE_1) {
			if (canSwitch && (currentCha != cha_id[0])) {
				SwitchChannel.switchChannel(this, cha_id[0], myHandler);
				switchCha = cha_id[0];
			}
		} else if (keyCode == KeyEvent.KEYCODE_2) {
			if (canSwitch && (currentCha != cha_id[1])) {
				SwitchChannel.switchChannel(this, cha_id[1], myHandler);
				switchCha = cha_id[1];
			}
		} else if (keyCode == KeyEvent.KEYCODE_3) {
			if (canSwitch && (currentCha != cha_id[2])) {
				SwitchChannel.switchChannel(this, cha_id[2], myHandler);
				switchCha = cha_id[2];
			}
		} else if (keyCode == KeyEvent.KEYCODE_4) {
			if (canSwitch && (currentCha != cha_id[3])) {
				SwitchChannel.switchChannel(this, cha_id[3], myHandler);
				switchCha = cha_id[3];
			}

		} else if (keyCode == KeyEvent.KEYCODE_5) {
			if (canSwitch && (currentCha != cha_id[4])) {
				SwitchChannel.switchChannel(this, cha_id[4], myHandler);
				switchCha = cha_id[4];
			}

		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
				| keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			ProduceThread.seconds = 60;

		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// progressDialog = null;
	}

	/**
	 * @author lb 1.参数P 2.进度值P 3.返回值类型R
	 */
	// private class ChannelAsyncTask extends AsyncTask<Void,Void,String[]>{
	//
	// @Override
	// protected String[] doInBackground(Void... params) {
	//
	// SLog.v("lfav", "doInBackground");
	// //获取用户喜爱的频道
	// favChaPkg = CAEProtocol.getFavChannel(0, 5);
	// // favChaPkg = null;
	// if(favChaPkg == null){
	// SLog.d("lfav", "in_if");
	// handleCAE.sendEmptyMessage(INSTANCE_NULL);
	// SLog.d("lfav", "in_loop---->获取频道信息失败");
	// return null;
	// }
	// /*
	// * 返回FavChannelPagekage类型
	// * 頻道和返回码标识的意思
	// * return_code:
	// * 4006000 成功
	// * 4006001 成功，但是数据库没有请求个数那么多的频道，正常情况很少出现
	// * 4006002 数据库不存在或丢失
	// * 4006003 操作数据库发生错误
	// * 4006004 未知错误，此种情况下UI可以重新请求
	// */
	// return_code = favChaPkg.getReturn_code();
	// // return_code = 4006004;
	// SLog.v("lfav", "return_code---->"+return_code);
	// if (return_code == 4006002 || return_code ==4006003) {
	// // Toast.makeText(FavoriteChannelActivity.this, "请求频道信息失败", 1000).show();
	// // ProduceThread.canRun = false;
	// SLog.v("lfav", "数据库有问题 = " + return_code);
	// handleCAE.sendEmptyMessage(DB_ERRO);
	// return null;
	// }
	// else if(return_code == 4006004){
	// SLog.v("lfav", "未知问题 = " + return_code);
	// handleCAE.sendEmptyMessage(UNKNOW_ERRO);
	// return null;
	// }
	//
	// ArrayList<FavChannelBean> channelList = favChaPkg.getChannels();
	// cha_count = channelList.size();
	// SLog.v("lfav", "cha_count------>"+cha_count);
	// cha_names = new String[cha_count];
	// cha_id = new int[cha_count];
	// for(int i=0;i<cha_count;i++){
	// FavChannelBean channelBean = (FavChannelBean) channelList.get(i);
	// cha_names[i] = channelBean.getChannel_name();
	// cha_id[i] = channelBean.getChannel_id();
	// }
	// return cha_names;
	// }
	//
	// @Override
	// protected void onPostExecute(String[] result) {
	// super.onPostExecute(result);
	// SLog.v("lfav", "onPostExecute");
	//
	// if(result == null){
	// SLog.v("lfav", "结果为null");
	// LocateToast.locateToast(FavoriteChannelActivity.this, 200,
	// "获取频道列表失败，请退出重试");
	// return;
	// }
	// canToNext = true;
	// chaListView.setAdapter(new ChannelAdapter());
	// cha_bar.setVisibility(View.GONE);
	// canSwitch = true;
	// // }
	// }
	// }

	/**
	 * 
	 */
	// private class ChannelAdapter extends BaseAdapter{
	//
	//
	//
	// public int getCount() {
	// // TODO Auto-generated method stub
	//
	// return cha_count;
	// }
	//
	// public Object getItem(int position) {
	// // TODO Auto-generated method stub
	// return null;
	// }
	//
	// public long getItemId(int position) {
	// // TODO Auto-generated method stub
	// return 0;
	// }
	//
	// public View getView(int position, View convertView, ViewGroup parent) {
	// // TODO Auto-generated method stub
	// if(convertView == null){
	// LayoutInflater flater =
	// LayoutInflater.from(FavoriteChannelActivity.this);
	// convertView = flater.inflate(R.layout.channel_item, null);
	// }
	// TextView chaIndex = (TextView) convertView.findViewById(R.id.channel_id);
	// TextView chaName = (TextView)
	// convertView.findViewById(R.id.channel_name);
	// chaIndex.setText(""+(position+1));
	// chaName.setText(cha_names[position]);
	// return convertView;
	// }
	//
	// }
}